package phone.qyg.com.qyg.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.SystemPrintl;
import com.app.utils.TransformController;
import com.app.view.CircleImageView;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.zfdang.multiple_images_selector.ImagesSelectorActivity;
import com.zfdang.multiple_images_selector.SelectorSettings;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.UserInfo;
import phone.qyg.com.qyg.utils.AppHttpRequest;
import phone.qyg.com.qyg.utils.PopuTypeSelectState;

/**
 * 作者：lblbh on 2017/12/4 15:16
 * 邮箱：lanbuhan@163.com
 * 功能：App用户信息
 */
@ContentView(R.layout.update_info)
public class UpdateInfoActivity extends BaseActivity {
    final int DATE_DIALOG = 1;
    final int REQUEST_CODE = 1131;

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.female)
    TextView female;

    @ViewInject(R.id.male)
    TextView male;

    @ViewInject(R.id.update_four)
    TextView update_four;

    @ViewInject(R.id.update_six)
    TextView update_six;

    @ViewInject(R.id.update_seven)
    TextView update_seven;

    @ViewInject(R.id.update_eight)
    TextView update_eight;

    @ViewInject(R.id.submit)
    TextView submit;

    @ViewInject(R.id.update_one)
    EditText update_one;

    @ViewInject(R.id.update_two)
    EditText update_two;

    @ViewInject(R.id.update_five)
    EditText update_five;

    @ViewInject(R.id.img)
    CircleImageView img;

    List<String> tranImgs = new ArrayList<String>();

    int mYear = ApplicationConfig.YEAR;

    int mMonth = ApplicationConfig.MONTH;

    int mDay = ApplicationConfig.DAY;

    Base maritalTheme;//婚姻状态
    Base eduLevelTheme;//学历状态
    Base industryTheme;//行业状态

    UserInfo userInfo;

    int sex;//0-男 1-女

    @Override
    public void initData(Bundle savedInstanceState) {

        AppHttpRequest.getUserInfo(new AppHttpRequest.OnAppHttpListener() {
            @Override
            public void onAppHttpState(boolean isState, String result) {
                if(isState && JSONTool.isStatus(result)){
                    userInfo = JSONTool.jsonDefaluTranClazz(result,null,UserInfo.class);
                    setData();
                }
            }
        });

    }

    private void setData(){
        if(userInfo == null) return;
        setImgPath(userInfo.fixImgUrl,img, OptionImageUtils.getPersonIcon());
        update_one.setText(setAttributeText(userInfo.nick_name));
        update_two.setText(setAttributeText(userInfo.user_name));
        update_four.setText(setAttributeText(userInfo.birth_day));
        update_five.setText(setAttributeText(userInfo.work_unit));
        update_six.setText(setAttributeText(userInfo.maritalStatusName));
        update_seven.setText(setAttributeText(userInfo.eduLevelName));
        update_eight.setText(setAttributeText(userInfo.industryName));


        //female 女 male 男  0-男
        sex = userInfo.sex;
        CommonUtil.setTextViewDrawableDirection(female,4,(sex == 0)?R.drawable.update_normal:R.drawable.update_select);
        CommonUtil.setTextViewDrawableDirection(male,4,(sex == 1)?R.drawable.update_normal:R.drawable.update_select);
    }


    @Event(value = {R.id.back,R.id.img,R.id.update_four,R.id.update_six,
                    R.id.update_seven,R.id.update_eight,R.id.submit,
                    R.id.female,R.id.male})
    private void viewOnClick(View v){
        if((userInfo == null) && (v != back)){
            return;
        }
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
            case R.id.img:
                //头像
                addPath();
                break;
            case R.id.update_four:
                //生日
                showDialog(DATE_DIALOG);
                break;
            case R.id.update_six:

                PopuTypeSelectState.showDialog(this,ApplicationConfig.MARITAL, new PopuTypeSelectState.OnAlertOnClick() {
                    @Override
                    public void onClick(Base theme, int dataType, AlertDialog showAlert) {
                        if(theme.type == 1){
                            maritalTheme = theme;
                            update_six.setText(theme.title);
                        }

                        dismissDialog(showAlert);
                    }
                });
                break;
            case R.id.update_seven:

                PopuTypeSelectState.showDialog(this,ApplicationConfig.EDU_LEVEL, new PopuTypeSelectState.OnAlertOnClick() {
                    @Override
                    public void onClick(Base theme, int dataType, AlertDialog showAlert) {
                        if(theme.type == 1){
                            eduLevelTheme = theme;
                            update_seven.setText(theme.title);
                        }

                        dismissDialog(showAlert);
                    }
                });
                break;
            case R.id.update_eight:

                PopuTypeSelectState.showDialog(this,ApplicationConfig.INDUSTRY, new PopuTypeSelectState.OnAlertOnClick() {
                    @Override
                    public void onClick(Base theme, int dataType, AlertDialog showAlert) {
                        if(theme.type == 1){
                            industryTheme = theme;
                            update_eight.setText(theme.title);
                        }

                        dismissDialog(showAlert);
                    }
                });
                break;
            case R.id.female:
                //女
                sex = (sex == 0)?1:0;
                CommonUtil.setTextViewDrawableDirection(female,4,(sex == 0)?R.drawable.update_normal:R.drawable.update_select);
                CommonUtil.setTextViewDrawableDirection(male,4,(sex == 1)?R.drawable.update_normal:R.drawable.update_select);
                break;
            case R.id.male:
                //男
                sex = (sex == 0)?1:0;
                CommonUtil.setTextViewDrawableDirection(female,4,(sex == 0)?R.drawable.update_normal:R.drawable.update_select);
                CommonUtil.setTextViewDrawableDirection(male,4,(sex == 1)?R.drawable.update_normal:R.drawable.update_select);
                break;
            case R.id.submit:
                SystemPrintl.systemPrintl("我在点击修改信息---->>>");
                String nick_name = getEditToString(update_one);
                String user_name = getEditToString(update_two);

                if(!isRequestStr(nick_name)){
                    PromptManager.showToast(R.string.nick_empty);
                    return;
                }
                if(!isRequestStr(user_name)){
                    PromptManager.showToast(R.string.user_name_empty);
                    return;
                }
                String birth_day = getEditToString(update_four);
                String work_unit = getEditToString(update_five);

                /**
                 * String nick_name,String user_name,String birth_day,String work_unit,
                 int sex,int marital_status,int edu_level,int industry
                 */
                UserInfo temp = new UserInfo(nick_name,user_name,birth_day,work_unit,
                        sex,
                        (maritalTheme == null)?userInfo.marital_status:maritalTheme.id,
                        (eduLevelTheme == null)?userInfo.edu_level:eduLevelTheme.id,
                        (industryTheme == null)?userInfo.industry:industryTheme.id);

                String dataValue = JSON.toJSONString(temp);

                mapKeys.put(AppHttpKey.DATA,dataValue);

                Xutils.UpLoadImgs(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.UPDATE_USER_MSG,
                        mapKeys,
                        tranImgs,
                        new MyCallBack<String>(){
                            @Override
                            public void onSuccess(String result) {
                                super.onSuccess(result);

                                if(JSONTool.isStatus(result)){
                                    PromptManager.showToast(R.string.update_info_sucess);
                                    SystemPrintl.systemPrintl("信息修改成功");
                                    AppHttpRequest.getUserInfo(new AppHttpRequest.OnAppHttpListener() {
                                        @Override
                                        public void onAppHttpState(boolean isState, String result) {
                                            Intent intent = new Intent(ApplicationConfig.APP_QX_LOGIN);
                                            intent.putExtra(TransformController.ChangeKEY.INTENT_KEY,result);
                                            LocalBroadcastManager.getInstance(QXApplication.getContext()).sendBroadcast(intent);
                                            UpdateInfoActivity.this.finish();
                                        }
                                    });

                                }
                            }
                        });
                break;
        }
    }

    /**
     *头像处理
     */
    private void addPath() {
        Intent intent = new Intent(this, ImagesSelectorActivity.class);
        intent.putExtra(SelectorSettings.SELECTOR_MAX_IMAGE_NUMBER, 1);
        intent.putExtra(SelectorSettings.SELECTOR_MIN_IMAGE_SIZE, 100000);
        intent.putExtra(SelectorSettings.SELECTOR_SHOW_CAMERA, true);
        intent.putStringArrayListExtra(SelectorSettings.SELECTOR_INITIAL_SELECTED_LIST, (ArrayList<String>) tranImgs);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // get selected images from selector
        if (requestCode == REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                tranImgs = data.getStringArrayListExtra(SelectorSettings.SELECTOR_RESULTS);
                if(isRequestList(tranImgs)){
                    CommonUtil.runOnUIThread(new Runnable() {
                        @Override
                        public void run() {
                            setImgPath("file://"+tranImgs.get(0),img, OptionImageUtils.getPersonIcon());
                        }
                    });
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /******设置时间*******/
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear + 1;
            mDay = dayOfMonth;
            setRegisTime();
        }
    };
    /**
     * 设置时间
     */
    private void setRegisTime(){
        String time = mYear +"-"+String.format(Locale.CHINA,"%02d", mMonth)+"-"+String.format(Locale.CHINA,"%02d", mDay);
        update_four.setText(time);
    }


    @Override
    public void initSucessView() {}
    @Override
    public void initViewHandler() {}
}
